// pages/my/score/index.js
const APP = getApp()
const WXAPI = require('apifm-wxapi')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scoreLogs: [],
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false
  },

  onLoad() {
    // 多语言初始化（若项目使用）
    if (getApp().initLanguage) {
      getApp().initLanguage(this)
    }
    // 首次加载
    this.resetAndLoad()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.resetAndLoad(() => wx.stopPullDownRefresh())
  },

  // 触底加载更多
  onReachBottom() {
    if (!this.data.hasMore || this.data.loading) return
    this.loadMore()
  },

  // 重置并加载
  resetAndLoad(done) {
    this.setData({ page: 1, hasMore: true, scoreLogs: [] }, () => {
      this.fetchScoreLogs().finally(() => typeof done === 'function' && done())
    })
  },

  // 加载更多
  loadMore() {
    this.setData({ page: this.data.page + 1 }, () => {
      this.fetchScoreLogs(true)
    })
  },

  // 拉取积分日志
  async fetchScoreLogs(append = false) {
    if (this.data.loading) return
    this.setData({ loading: true })
    try {
      const { page, pageSize } = this.data
      const res = await WXAPI.scoreLogs({
        token: wx.getStorageSync('token'),
        page,
        pageSize
      })
      if (res.code === 0) {
        const list = res.data.result || []
        const next = append ? this.data.scoreLogs.concat(list) : list
        this.setData({
          scoreLogs: next,
          hasMore: list.length >= pageSize
        })
      } else {
        this.setData({ hasMore: false })
      }
    } catch (e) {
      console.error('fetchScoreLogs error', e)
      this.setData({ hasMore: false })
    } finally {
      this.setData({ loading: false })
    }
  }
})